﻿import plugin from "../../lib/plugins/plugin.js";
import common from "../../lib/common/common.js";
import gsCfg from '../../plugins/genshin/model/gsCfg.js'
import yaml from "yaml"
import fs from "fs";
import sharp from 'sharp'
import pLimit from 'p-limit'

let maxnum = 30  //并发限制

let NumReg = '[一壹二两三四五六七八九十百千万亿\\d]+'
let cooldowns = new Map();
//1.定义命令规则
export class example extends plugin {
  constructor() {
    super({
      /** 功能名称 */
      name: '随机setu',
      /** 功能描述 */
      dsc: '简单开发示例',
      /** https://oicqjs.github.io/oicq/#events */
      event: 'message',
      /** 优先级，数字越小等级越高 */
      priority: 5000,
      rule: [
		{
          reg: '^#(随机|来点)(r18)?(瑟瑟|涩涩|瑟图|铯图|色图|涩图|好看的|setu)(r18)?(.*)$', 
          fnc: 'radomsetu'
        }
      ]
    })
  }


 async radomsetu(e) {
	if (!e.isGroup) {
	    return;
    }
	let groupId = e.group_id
    let cfg = await loadcfg(groupId)
	if (!cfg && !e.isMaster) return
	
    if (!cfg.setu && !e.isMaster) {
	     logger.mark(`${groupId} 涩图权限 ${cfg.setu}`)
         return;
    }
    let num = e.msg.match(new RegExp(`(${NumReg})(张|份)`));
    if (!num) {
      num = 10
    } else {
      num = Number(num[1]);
	  if (isNaN(num)) {
             e.reply('请输入阿拉伯数字');
             return;
            }
    }
	
	if (num > 30) { 
        num = 30
	}
    if (!e.isMaster ) {
	    const cooldown = cooldowns[groupId];
	    if (cooldown && cooldown > Date.now()) {
            const remainingTime = Math.ceil((cooldown - Date.now()) / 1000);
            e.reply(`lsp注意身体，请${remainingTime}秒后再来～`,false,{ recallMsg: 5 });
            return;
        }
	}
	let sort = 'pixiv'
	if (e.msg.includes('r18') && cfg.r18) {
		sort = 'r18'
	} else if (e.msg.includes('r18') && e.isMaster) {
		sort = 'r18'
	}
	let response = ''
	let res = ''
	let url = `https://api.anosu.top/img?sort=${sort}&num=${num}&type=json&proxy=i.yuki.sh&time=${Date.now()}`
	try {
	    response = await fetch(url);
		res = await response.json();
	} catch(error) {
		e.reply('请求失败')
		return
	}
	// 只有在请求成功时才设置CD
    if (!e.isMaster) {
        cooldowns[groupId] = Date.now() + cfg.cd * 1000;
    }
    e.reply(`${sort == 'r18' ? 'r8' : ''}图片马上来力，数量${num}...`,false,{ recallMsg: 5 })
    let msgs = []
	// 设置并发限制
    const limit = pLimit(maxnum)
    // 使用 Promise.all 和 p-limit 并行下载图片
        await Promise.all(res.pics.map((k, index) => limit(async () => {
            try {
				const image = await fetch(k);
                const imagedate = Buffer.from(await image.arrayBuffer());
                const flippedImage = await sharp(imagedate).flop().toBuffer();
                msgs.push(segment.image(flippedImage))  
			    logger.mark(`anosu 图片${index+1}处理 成功`)
			} catch(error) {	
				logger.error(`anosu 图片${index+1}处理 失败`)
			}	
        })));
	
	let ForwardMsg = await common.makeForwardMsg(e,[msgs]); 
    await e.reply(ForwardMsg,false,{ recallMsg: msgs.length > 10 ? cfg.recall : 60 });//回复消息
	
        return true
 }

}

async function loadcfg(id) {
	let file = `data/pixiv.yaml`
    if (!fs.existsSync(file)) return false
	
    let data = yaml.parse(fs.readFileSync(file, 'utf8'))
	if (!data[id]) return false
	
	return data[id]
}